package com.glsc.ngateway.flowable.amqp;

import cn.hutool.core.thread.ThreadUtil;
import cn.hutool.core.util.StrUtil;
import com.glsc.ngateway.flowable.util.GatewayExecutionCompensationUtil;
import com.rabbitmq.client.Channel;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.amqp.rabbit.annotation.RabbitHandler;
import org.springframework.amqp.rabbit.annotation.RabbitListener;
import org.springframework.stereotype.Component;

import javax.annotation.Resource;

/**
 * @author lium
 * @date 2021/09/24
 * mq 监听
 */
@Component
//@RabbitListener(queues = "flowable.queue.tasknotify")//监听对列消息
public class MessageReceiver {
    private static final Logger logger = LoggerFactory.getLogger(MessageReceiver.class);

    @Resource
    GatewayExecutionCompensationUtil util;

    @RabbitListener(queues = {InitQueue.QUEUE_CHECKGW})
    @RabbitHandler
    public void processReport(org.springframework.amqp.core.Message messageObject, Channel channel) {
        logger.info("~~~~~~ MessageReceiver is :" + messageObject);
        boolean ackFlag = true;
        Exception exception = null;
        try {
            ThreadUtil.safeSleep(1000);
            util.checkAndCompensation(StrUtil.utf8Str(messageObject.getBody()));
        } catch (Exception e) {
            ackFlag = false;
            exception = e;
            logger.warn("MQ任务处理异常,", e);
        } finally {
            try {
                if (ackFlag) {
                    channel.basicAck(messageObject.getMessageProperties().getDeliveryTag(), false);
                } else {
                    logger.error("MQ任务处理异常:" + messageObject, exception);
                    channel.basicNack(messageObject.getMessageProperties().getDeliveryTag(), false, false);
                }
            } catch (Exception e) {
                logger.warn("MQ任务处理异常:" + messageObject, exception);
            }
        }
    }
}


